/*********************************************************************************
 *      Copyright:  (C) 2024 YunQi
 *                  All rights reserved.
 *
 *       Filename:  adc_mq2.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(26/04/24)
 *         Author:  dengleen <dengleen@outlook.com>
 *      ChangeLog:  1, Release initial version on "26/04/24 04:25:45"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

//#include "logger.h"
#include "adc_mq2.h"

int get_smokescope(float *smokescope)
{
	int         fd;
	char        filename[20];
	int         adapter_num = 1;

	char        config[2];
	char        data[1];
	int         i;
	int         value;
	float       voltage;
	float       sum;


	memset(filename, 0, sizeof(filename));
	snprintf(filename, sizeof(filename), "/dev/i2c-%d", adapter_num);
	fd = open(filename, O_RDWR);
	if(fd < 0)
	{
//		log_error("Failed to open the i2c bus");
		close(fd);
		return -1;
	}

	if(ioctl(fd, I2C_SLAVE, PCF8591_ADDRESS) < 0)
	{
//		log_error("Failed to acquire bus access and/or talk to slave");
		close(fd);
		return -2;
	}

	memset(config, 0, sizeof(config));
	config[0] = PCF8591_AINO;
	if(write(fd, config, 1) < 0)
	{
//		log_error("Write to i2c failed\n");
		close(fd);
		return -3;
	}
	sleep(1);

	for(i=0; i<2; i++)
	{
		memset(data, 0, sizeof(data));
		if(read(fd, data, 1) < 0)
		{
//			log_error("read data failed\n");
			close(fd);
			return -4;
		}
	}
	value = (int)data[0];

	voltage = (value / 255.0) * VOLTAGE_REF;
	sum = voltage / VOLTAGE_REF;
	*smokescope = sum * 100;

//	log_info("MQ-2 实际电压值: %.2fV, 烟雾浓度: %.2f%\n", voltage, *smokescope);
	sleep(1);

	close(fd);
	return 0;
}

int main() {
    float smokescope;
    int result;

    result = get_smokescope(&smokescope);

    if (result == 0) {
        // 成功获取烟雾浓度
        printf("成功获取 MQ - 2 传感器数据，烟雾浓度: %.2f%%\n", smokescope);
    } else {
        // 处理错误情况
        switch (result) {
            case -1:
                printf("错误: 无法打开 I2C 总线\n");
                break;
            case -2:
                printf("错误: 无法获取总线访问权限或与从设备通信失败\n");
                break;
            case -3:
                printf("错误: 向 I2C 写入数据失败\n");
                break;
            case -4:
                printf("错误: 从 I2C 读取数据失败\n");
                break;
            default:
                printf("未知错误，错误码: %d\n", result);
                break;
        }
    }

    return 0;
}
